import axios from 'axios'
import 'antd-mobile/dist/antd-mobile.css'
import { Toast } from 'antd-mobile';
import React from 'react';
import { Redirect } from 'react-router-dom'

//创建axios实例
const service = axios.create({
    baseURL: process.env.BASE_API, // api的base_url
    timeout: 200000, // 请求超时时间
    withCredentials: true // 选项表明了是否是跨域请求
})
service.interceptors.request.use(config => {
    Toast.loading('加载中', 0)              // loading组件，显示文字加载中，自动关闭延时1s
    console.log('request go');
    return config;
}, err => {
    console.log('请求失败')
    return Promise.reject(err)
})
//拦截响应
service.interceptors.response.use(config => {
    Toast.hide()                             // 销毁Toast组件
    console.log('response get')
    return config;
}, err => {
    console.log('响应失败')
    return Promise.reject(err)
})

// respone拦截器
service.interceptors.response.use(
    response => {
        /**
        * code为非000000是抛错 可结合自己业务进行修改
        */
        /* if (response.status !== 401) {
            console.log("response", res)
            res.code = res.data.code
            res.message = res.response.data.msg
            Toast.info(res.code + res.message, 2);
            return Promise.reject('error')
        } else {
            return response.data
        } */
        console.log('receive response:', response);
        return response.data;
    },
    error => {
        console.log('response error:', error.response) // for debug


        let code = error.response.status;

        let message = error.response.data.message;

        if (code === 404) {
            message = "请求的链接不存在"
        }

        if (code === 401) {
            /* '登陆已经过期,请重新登录',
            '确定登出',
            {
              confirmButtonText: '重新登录',
              cancelButtonText: '取消',
              type: 'warning'
            } */
            /*  Dialog.confirm({
                 title: '确定登出',
                 message: '登录已经过期,请重新登录',
                 confirmButtonText: '重新登录',
                 cancelButtonText: '取消'
             }).then(() => {
                 store.dispatch('logout').then(() => {
                     router.push('/login');
                 })
             }) */
        }

        Toast.fail(
            message,
            2,
            () => {
                return (
                    <>
                        <Redirect to="/" />
                    </>
                )
            }
        )
        return Promise.reject(message)
        // return Promise.reject(error)
    }
)
export default service